// hyb_yl/pharmacy/pages/shop_list/shop_list.js
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    price_state: '',
    left_lab: 0,
    car_state: false,
    list: [],
    page: 0,
    keyword: "",
    type: "",
    total: 0,
    amountShop: 0
  },
  shop_car: function (e) {
    this.setData({
      car_state: !this.data.car_state
    })
  },
  lab_btn: function (e) {
    this.setData({
      type: e.currentTarget.dataset.id,
      page: 0,
      list: [],
    })
    this.getList();
  },
  price_btn: function (e) {
    if (this.data.price_state == 1) {
      this.setData({
        price_state: 2
      })
    } else if (this.data.price_state == 2) {
      this.setData({
        price_state: 1
      })
    } else {
      this.setData({
        price_state: 1
      })
    }
    this.setData({
      screen_state: ''
    })
  },
  choose_btn: function (e) {
    console.log(e)
    if (e.currentTarget.dataset.choose == '力度') {
      this.setData({
        screen_state: 1
      })
    } else if (e.currentTarget.dataset.choose == '销量') {
      this.setData({
        screen_state: 2
      })
    }
    this.setData({
      price_state: ''
    })
  },
  todetail:function(e){
    wx.navigateTo({
      url: '/hyb_yl/mysubpages/pages/product/product?sid='+e.currentTarget.dataset.sid,
    })
  },
  changekeyword: function (e) {
    var that = this;
    that.setData({
      keyword: e.detail.value
    })
  },
  searchs: function (e) {
    var that = this;
    that.setData({
      page: 0,
      list: []
    })
    that.getList();
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var hid = options.hid;
    var that = this;
    var agentname = options.agentname;
    that.setData({
      hid: hid,
      agentname: agentname
    })
    wx.setNavigationBarTitle({
      title: agentname,
    })

  },
  //加入购物车
  addcar: function (e) {
    console.log(e)
    var num = e.currentTarget.dataset.num
    console.log(num)
    var ifcfy = e.currentTarget.dataset.ifcfy
    var g_kuaidi = e.currentTarget.dataset.g_kuaidi
    var gg_name = e.currentTarget.dataset.drugName
    var num = e.currentTarget.dataset.num;
    if (num == 0) {
      num = 1
    }
    var mostgt = e.currentTarget.dataset.mostgt
    var gg_ke = e.currentTarget.dataset.gg_ke
    var gg_id = e.currentTarget.dataset.gg_id
    var addressid = e.currentTarget.dataset.addressid //收货地址id
    var shopList = {
      sid: e.currentTarget.dataset.sid,
      sname: e.currentTarget.dataset.sname,
      sthumb: e.currentTarget.dataset.sthumb,
      snum: e.currentTarget.dataset.snum,
      hid:e.currentTarget.dataset.hid,
      surplus:e.currentTarget.dataset.surplus,
      agentname:e.currentTarget.dataset.agentname,
      num: 1,
      smoney: e.currentTarget.dataset.smoney,
      g_kuaidi: g_kuaidi,
      gg_name: gg_name,
      mostgt: mostgt,
      gg_ke: gg_ke,
      ifcfy: ifcfy,
      gg_id: gg_id,
      addressid: addressid
    }
    console.log(shopList)
    var shopcar = wx.getStorageSync('shopcar') || []
    var amountShop = this.data.amountShop
    if (shopcar.length > 0) {
      for (var i in shopcar) {
        if (shopcar[i].sid == shopList.sid) {
          if (shopcar[i].gg_id == shopList.gg_id) {
            shopcar[i].num = shopcar[i].num + 1
            console.log(shopcar[i].num)
            if (shopcar[i].mostgt == 0) {
              if (shopcar[i].num > shopcar[i].snum) {
                shopcar[i].num = shopcar[i].snum
                try {
                  wx.setStorageSync('shopcar', shopcar)
                  amountShop = amountShop
                  this.setData({
                    // amountShop:amountShop,
                    num: 1
                  })
                } catch (e) {
                  console.log(e)
                }
                wx.showToast({
                  title: '加入购物车成功！',
                  icon: 'success',
                  duration: 2000
                });
                return;
              }
            } else {
              if (shopcar[i].num > shopcar[i].mostgt) {
                shopcar[i].num = shopcar[i].mostgt
                try {
                  wx.setStorageSync('shopcar', shopcar)
                  console.log(shopcar)
                  amountShop = amountShop
                  // amountShop =amountShop + shopList.num
                  // console.log(amountShop)
                  this.setData({
                    // amountShop:amountShop,
                    num: 1
                  })
                } catch (e) {
                  console.log(e)
                }
                wx.showToast({
                  title: '加入购物车成功！',
                  icon: 'success',
                  duration: 2000
                });
                return;
              }

            }
            try {
              wx.setStorageSync('shopcar', shopcar)
              amountShop = amountShop + shopList.num
              console.log(amountShop)
              this.setData({
                amountShop: amountShop,
                num: 1
              })
            } catch (e) {
              console.log(e)
            }
            wx.showToast({
              title: '加入购物车成功！',
              icon: 'success',
              duration: 2000
            });

            // 返回（在if内使用return，跳出循环节约运算，节约性能） 
            return;
          }
        }
      }
      shopcar.push(shopList)
      amountShop = amountShop + shopList.num
      this.setData({
        amountShop: amountShop,
        num: 1
      })
    } else {
      shopcar.push(shopList)
      amountShop = amountShop + shopList.num
      this.setData({
        amountShop: amountShop,
        num: 1
      })
    }


    try {
      wx.setStorageSync('shopcar', shopcar)
      this.setData({
        carlist:shopcar
      })
      this.getcar();
      this.amountShop();
      this.getTotalPrice();
      // 返回（在if内使用return，跳出循环节约运算，节约性能） 
      //关闭窗口
      wx.showToast({
        title: '加入购物车成功！',
        icon: 'success',
        duration: 2000
      });
      this.setData({
        choseprod: true
      })
      return;
    } catch (e) {
      console.log(e)
    }

  },
  getBase: function () {
    var that = this
    app.util.request({
      'url': 'entry/wxapp/index.adv',
      'cachetime': '30',
      data: {
        position: 19
      },
      success: function (res) {
        console.log(res)
        var imageArr = res.data
        that.setData({
          imageArr: imageArr
        })
      }
    })
  },
  getHospital: function () {
    var that = this;
    app.util.request({
      'url': "entry/wxapp/Goods.hospital_detail",
      data: {
        hid: that.data.hid
      },
      success: function (res) {
        that.setData({
          info: res.data
        })
      }
    })
  },
  tojiesuan: function () {
    wx.navigateTo({
      url: '/hyb_yl/pharmacy/pages/distribution/distribution?from=hos_detail',
    })
  },
  // 获取药品列表
  getList: function () {
    var that = this;
    app.util.request({
      'url': "entry/wxapp/goods.goods_list",
      data: {
        hid: that.data.hid,
        page: that.data.page,
        type: that.data.type,
        keyword: that.data.keyword
      },
      success: function (res) {
        var page = that.data.page + 1;

        that.setData({
          list: that.data.list.concat(res.data),
          page: page
        })
        that.getcar();

      }
    })
  },
  // 获取购物车列表
  getcar: function () {
    var that = this;
    var list = that.data.list;
    var carlist = wx.getStorageSync('shopcar');

    for (var i = 0; i < list.length; i++) {
      if(carlist.length == 0)
      {
        list[i]['num'] = 0
      }
      for (var j = 0; j < carlist.length; j++) {
        if (list[i].sid == carlist[j]['sid']) {
          list[i]['num'] = carlist[j]['num']
        }
      }

    }
    console.log(list);
    console.log(carlist)
    that.setData({
      list: list,
    })
  },
  // 获取药品分类
  getType: function () {
    var that = this;
    app.util.request({
      url: "entry/wxapp/goods.goods_type",
      success: function (res) {
        console.log(res)
        var type_list = res.data.list
        that.setData({
          type_list: type_list,
        })
      },
    });
  },
  // 加
  add: function (e) {
    console.log(e)
    var index = e.currentTarget.dataset.index
    var carlist = this.data.carlist

    if (carlist[index].check) {
      carlist[index].num++;
      wx.setStorageSync('shopcar', carlist)
      this.getTotalPrice()
    } else {
      carlist[index].num++;
    }
    if (carlist[index].mostgt == 0) {
      if (carlist[index].num > parseInt(carlist[index].snum)) {
        wx.showToast({
          title: '您最多能买' + carlist[index].snum + '件商品',
          icon: 'none'
        })
        carlist[index].num = carlist[index].snum
        this.setData({
          carlist: carlist
        })
        wx.setStorageSync('shopcar', carlist)
        this.getTotalPrice()
      }
    } else {
      if (carlist[index].num > parseInt(carlist[index].mostgt)) {
        wx.showToast({
          title: '商品不能超过' + carlist[index].mostgt + '个',
          icon: 'none'
        })
        carlist[index].num = carlist[index].mostgt
        wx.setStorageSync('shopcar', carlist)
        this.getTotalPrice()
        this.setData({
          carlist: carlist
        })
      }
    }
    this.setData({
      carlist: carlist
    })
    wx.setStorageSync('shopcar', carlist)
    this.getcar();
    this.amountShop();
    this.getTotalPrice();
  },
  // 减
  even: function (e) {
    var index = e.currentTarget.dataset.index
    var carlist = this.data.carlist
    if (carlist[index].check) {
      carlist[index].num--;
      if (carlist[index].num < 1) {
        wx.showToast({
          title: '至少一件商品',
          icon: "none"
        })
        carlist[index].num = 1
      }
      wx.setStorageSync('shopcar', carlist)
      this.getTotalPrice()
    } else {
      carlist[index].num--;
      if (carlist[index].num < 1) {
        wx.showToast({
          title: '至少一件商品',
          icon: "none"
        })
        carlist[index].num = 1
      }
    }
    this.setData({
      carlist: carlist
    })
    wx.setStorageSync('shopcar', carlist)

    this.getcar();
    this.amountShop();
    this.getTotalPrice();
  },
  // 计算总价
  getTotalPrice() {
    let carlist = wx.getStorageSync('shopcar');  // 获取购物车列表
    console.log(carlist)
    let total = 0;
    for (let i = 0; i < carlist.length; i++) {

      total += carlist[i].smoney * carlist[i].num

      console.log(total)
    }
    this.setData({
      total: total.toFixed(2)
    })
    console.log(total)
  },
  // 清空购物车操作
  clear_car: function () {
    var that = this;
    wx.setStorageSync('shopcar', '');
    that.setData({
      carlist: [],
      total: 0
    })
    this.getcar();
    this.amountShop();
    this.getTotalPrice();
  },
  // 拨打电话
  tocall: function (e) {
    var phone = e.currentTarget.dataset.telphone
    wx.makePhoneCall({
      phoneNumber: phone,
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    that.getHospital();
    that.getList();
    that.getType();
    that.getBase();
    var carlist = wx.getStorageSync('shopcar')
    that.setData({
      carlist: carlist
    })
    that.amountShop();
    that.getTotalPrice();
  },
  amountShop() {
    var amountShop = 0;
    var shopcar = wx.getStorageSync('shopcar')
    console.log(shopcar)
    for (var i = 0; i < shopcar.length; i++) {
      amountShop = parseFloat(amountShop) + parseFloat(shopcar[i].num)
    }
    this.setData({
      amountShop: amountShop
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})